import { reqGetCode,reqUserRegister,reqUserLogin,reqUserInfo,reqUserLogout} from "@/api";

const state ={
    //验证码
    code:'',
    token:localStorage.getItem('TOKEN'),
    //用户信息
    userInfo:{}
};
const mutations={
    GETCODE(state,value){
        state.code=value
    },
    USERLOGIN(state,value){
        state.token=value;
    },
    GETUSERINFO(state,value){
        state.userInfo=value
    },
    USERLOGOUT(state){
        state.token='';
        state.userInfo={}
        state.code=''
    },
};
const actions = {
    //获取验证码
   async getCode(context,phone){
       let result= await reqGetCode(phone);
    //    console.log(result);
       if(result.code==200){
          context.commit('GETCODE',result.data);
           return 'ok'
       }else{
           return Promise.reject(new Error('faile'));
       }
    },
    //用户注册
    async userRegister(context,user){
        let result= await reqUserRegister(user);
        if(result.code==200){
            return 'ok'
        }else{
            return Promise.reject(new Error(result.message));
        }
    },
    //用户登陆
    async userLogin(context,user){
        let result= await reqUserLogin(user);
        if(result.code==200){
            context.commit('USERLOGIN',result.data.token)
            //持久化存储token
            localStorage.setItem('TOKEN',result.data.token);
            return 'ok'
        }else{
            return Promise.reject(new Error(result.message));
        }
    },
    //获取用户信息
    async getUserInfo(context){
        let result= await reqUserInfo();
        if(result.code==200){
            context.commit('GETUSERINFO',result.data)
            return 'ok'
        }else{
            return Promise.reject(new Error(result.message));
        }
    },
     //用户退出登陆
    async userLogout(context,user){
        let result= await reqUserLogout();
        if(result.code==200){
            context.commit('USERLOGOUT')
            //清空存储的token
            localStorage.removeItem('TOKEN');
            return 'ok'
        }else{
            return Promise.reject(new Error(result.message));
        }
    },
};
const getters={

};

export default {
    namespaced: true,
    state,
    actions,
    mutations,
    getters
}